package org.jeecg.modules.mes.chiefdata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataBom;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataBomitem;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataMateriel;
import org.jeecg.modules.mes.chiefdata.entity.MesChiefdataReplacematerial;
import org.jeecg.modules.mes.chiefdata.mapper.MesChiefdataBomMapper;
import org.jeecg.modules.mes.chiefdata.mapper.MesChiefdataBomitemMapper;
import org.jeecg.modules.mes.chiefdata.service.IMesChiefdataBomService;
import org.jeecg.modules.mes.chiefdata.service.IMesChiefdataMaterielService;
import org.jeecg.modules.mes.chiefdata.service.IMesChiefdataReplacematerialService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @Description: 主数据—BOM
 * @Author: jeecg-boot
 * @Date: 2020-10-20
 * @Version: V1.0
 */
@Service
public class MesChiefdataBomServiceImpl extends ServiceImpl<MesChiefdataBomMapper, MesChiefdataBom> implements IMesChiefdataBomService {

    @Autowired
    private MesChiefdataBomMapper mesChiefdataBomMapper;
    @Autowired
    private MesChiefdataBomitemMapper mesChiefdataBomitemMapper;
    @Autowired
    private IMesChiefdataMaterielService mesChiefdataMaterielService;
    @Autowired
    private ISysDictService sysDictService;

    /**
     * 替代料
     */
    @Autowired
    private IMesChiefdataReplacematerialService mesChiefdataReplacematerialService;

    @Override
    @Transactional
    public void delMain(String id) {
        mesChiefdataBomitemMapper.deleteByMainId(id);
        mesChiefdataBomMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            mesChiefdataBomitemMapper.deleteByMainId(id.toString());
            mesChiefdataBomMapper.deleteById(id);
        }
    }

    @Transactional
    public boolean importMesChiefdataBom(Map<String, MultipartFile> fileMap) {
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                int i = 0;
                List<MesChiefdataBom> list = ExcelImportUtil.importExcel(file.getInputStream(), MesChiefdataBom.class, params);
                for (MesChiefdataBom bom : list) {
                    //通过料号查询物料是否存在
                    if (StringUtils.isBlank(bom.getMachinesortCode())) {
                        throw new RuntimeException("成品料号不能为空！请检查！");
                    }
                    if (StringUtils.isBlank(bom.getProductCode())) {
                        throw new RuntimeException("商品编码不能为空！请检查！");
                    }
                    if (StringUtils.isBlank(bom.getQuery2())) {
                        throw new RuntimeException("生产阶别不能为空！请检查！");
                    }
                    if (this.checkProduceGrade(bom.getQuery2())) {
                        throw new RuntimeException("生产阶别错误！请检查！");
                    }
                    //对料号做首尾去空格
                    LambdaQueryWrapper<MesChiefdataMateriel> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(MesChiefdataMateriel::getMaterielCode, bom.getMachinesortCode().trim());
                    List<MesChiefdataMateriel> materiels = mesChiefdataMaterielService.list(queryWrapper);
                    if (materiels.size() == 0) {
                        MesChiefdataMateriel mesChiefdataMateriel = new MesChiefdataMateriel();
                        mesChiefdataMateriel.setMaterielCode(bom.getMachinesortCode());
                        mesChiefdataMateriel.setProductCode(bom.getProductCode());
                        mesChiefdataMateriel.setProductName(bom.getMaterialName());
                        mesChiefdataMateriel.setUnit(bom.getUnit());
                        mesChiefdataMateriel.setMaterielType(bom.getMaterialType());
                        mesChiefdataMateriel.setGauge(bom.getMaterialGauge());
                        mesChiefdataMaterielService.save(mesChiefdataMateriel);
                    }
                    mesChiefdataBomMapper.insert(bom);
                }
                return true;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new RuntimeException("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    private boolean checkProduceGrade(String produceGrade) {
        List<DictModel> dictModels = sysDictService.queryDictItemsByCode("produce_grade");
        for (DictModel dm : dictModels) {
            if (produceGrade.equals(dm.getValue())) {
                return false;
            }
        }
        return true;
    }


    /**
     * 更新替代料
     *
     * @param id
     * @return
     */
    @Transactional
    public boolean replacematerial(String id) {
        //bom主表信息
        MesChiefdataBom mesChiefdataBom = mesChiefdataBomMapper.selectById(id);
        mesChiefdataReplacematerialService.deleteMachineSort(mesChiefdataBom.getMachinesortCode());
        List<MesChiefdataReplacematerial> replacematerials = new ArrayList<>();
        QueryWrapper<MesChiefdataBomitem> datebom = new QueryWrapper<>();
        datebom.like("position_num", "替代");
        datebom.like("quantity", "0");
        datebom.eq("bom_id", id);
        //所有替代料
        List<MesChiefdataBomitem> mesChiefdataBomitems = mesChiefdataBomitemMapper.selectList(datebom);
        if (mesChiefdataBomitems.size() > 0) {
            //遍历替代料信息，获取替代料数据
            for (MesChiefdataBomitem item : mesChiefdataBomitems) {
                String tdnum = item.getPositionNum().trim().replace("替代", "");
                if (StringUtils.isNotBlank(tdnum)) {
                    QueryWrapper<MesChiefdataBomitem> datebom1 = new QueryWrapper<>();
                    datebom1.like("position_num", tdnum.trim());
                    datebom1.ne("quantity", "0");
                    datebom1.eq("bom_id", id);
                    List<MesChiefdataBomitem> mesChiefdataBomitems1 = mesChiefdataBomitemMapper.selectList(datebom1);
                    if (mesChiefdataBomitems1.size() == 1) {
                        MesChiefdataReplacematerial mesChiefdataReplacematerial = new MesChiefdataReplacematerial();
                        //成品料号
                        mesChiefdataReplacematerial.setMachineSort(mesChiefdataBom.getMachinesortCode());
                        mesChiefdataReplacematerial.setMachineEdition(mesChiefdataBom.getMaterialGauge());
                        //替代料料号
                        mesChiefdataReplacematerial.setReplaceCode(item.getMaterielCode());
                        mesChiefdataReplacematerial.setReplaceName(item.getMaterielName());
                        mesChiefdataReplacematerial.setReplaceGague(item.getMaterielGauge());
                        //主料料号
                        mesChiefdataReplacematerial.setMainCode(mesChiefdataBomitems1.get(0).getMaterielCode());
                        mesChiefdataReplacematerial.setMainName(mesChiefdataBomitems1.get(0).getMaterielName());
                        mesChiefdataReplacematerial.setMainGague(mesChiefdataBomitems1.get(0).getMaterielGauge());
                        mesChiefdataReplacematerialService.save(mesChiefdataReplacematerial);
                    } else {
                        throw new RuntimeException("更新替代料信息失败，替代料" + item.getMaterielCode() + "未匹配上位号" + tdnum + "的主物料，请手动添加所有该成品料号的替代料信息！");
                    }
                }
            }
            return true;
        } else {
            throw new RuntimeException("更新替代料信息失败，未找到替代料，请手动添加所有该成品料号的替代料信息！");
        }
    }
}
